﻿#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h> // For inet_ntop
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>    // For gethostbyname

int main() {
    const char* hostname = "example.com"; // 要查询的域名
    struct hostent* host_entry;
    char ipstr[INET6_ADDRSTRLEN]; // 用于存储 IP 地址的字符串

    // 执行 DNS 查询
    host_entry = gethostbyname(hostname);
    if (host_entry == NULL) {
        fprintf(stderr, "gethostbyname: 查询失败\n");
        return 1;
    }

    printf("IP addresses for %s:\n\n", hostname);

    // 遍历地址列表
    for (int i = 0; host_entry->h_addr_list[i] != NULL; i++) {
        void* addr;

        // 根据地址类型处理
        if (host_entry->h_addrtype == AF_INET) { // IPv4
            addr = host_entry->h_addr_list[i];
            inet_ntop(AF_INET, addr, ipstr, sizeof(ipstr));
            printf("  IPv4: %s\n", ipstr);
        }
        else if (host_entry->h_addrtype == AF_INET6) { // IPv6
            addr = host_entry->h_addr_list[i];
            inet_ntop(AF_INET6, addr, ipstr, sizeof(ipstr));
            printf("  IPv6: %s\n", ipstr);
        }
    }

    return 0;
}
